<script setup>
import { Edit, Delete } from '@element-plus/icons-vue'
import { artGetListService, artDelService } from '../../api/article'
import { watch, ref } from 'vue'
import ChannelSelect from './components/ChannelSelect.vue'
import ArticleEdit from './components/ArticleEdit.vue'
import { formatTime } from '@/utils/format.js'

const categoryId = ref('') //用户搜索时选中的分类id
const state = ref('') //用户搜索时选中的发布状态
const loading = ref(false) // loading状态
const articles = ref([]) //文章列表数据模型

//分页条数据模型
const pageNum = ref(1) //当前页
const total = ref(20) //总条数
const pageSize = ref(3) //每页条数

// 获取文章需传的参数
const params = ref({
  pageNum: pageNum.value,
  pageSize: pageSize.value,
  categoryId: categoryId.value ? categoryId.value : null,
  state: state.value ? state.value : null
})

const categorys = ref([]) //分类信息
const articleEditRef = ref() //引用子组件

//当每页条数发生了变化，调用此函数
const onSizeChange = (size) => {
  pageSize.value = size
  // 只要是每页条数变化了，那么原本正在访问的当前页意义不大了，数据大概率已经不在原来那一页了
  // 重新从第一页渲染即可
  params.value.pageNum = 1
  params.value.pageSize = size
  // 基于最新的当前页 和 每页条数，渲染数据
  articleList()
}
//当前页码发生变化，调用此函数
const onCurrentChange = (num) => {
  // 更新当前页
  params.value.pageNum = num
  // 基于最新的当前页，渲染数据
  articleList()
}

// 得到分类数据
const getCategorys = async (category) => {
  categorys.value = category
}
//获取文章列表数据
const articleList = async () => {
  loading.value = true
  const result = await artGetListService(params.value)
  // console.log('文章管理列表', result)

  // 渲染视图
  total.value = result.data.data.total
  articles.value = result.data.data.items
  loading.value = false
  //匹配id给属性分类名称
  for (let i = 0; i < articles.value.length; i++) {
    let article = articles.value[i]
    for (let j = 0; j < categorys.value.length; j++) {
      if (article.categoryId == categorys.value[j].id) {
        article.categoryName = categorys.value[j].categoryName
      }
    }
  }
}
//监视categorys数据
watch(
  () => categorys.value,
  async (newValue, oldValue) => {
    if (newValue !== oldValue) {
      await articleList()
    }
  }
)

// 头部--搜索逻辑 => 按照最新的条件，重新检索，从第一页开始展示
const onSearch = () => {
  params.value.pagenum = 1 // 重置页面
  articleList()
}
// 头部--重置逻辑 => 将筛选条件清空，重新检索，从第一页开始展示
const onReset = () => {
  params.value.pageNum = 1 // 重置页面
  params.value.categoryId = ''
  params.value.state = ''
  articleList()
}

//点击添加信息按钮
const onAddArticle = () => {
  articleEditRef.value.open({}) //添加传{}
}
// 点击编辑信息图标
const onEditArticle = (row) => {
  articleEditRef.value.open(row) //编辑传 row
}

// 添加或者编辑 成功的回调
const onSuccess = (type) => {
  if (type === 'add') {
    // 如果是添加，最好渲染最后一页
    const lastPage = Math.ceil((total.value + 1) / params.value.pageSize)
    // console.log(lastPage)
    // 更新成最大页码数，再渲染
    params.value.pageNum = lastPage
  }
  articleList()
}

// 点击删除图标
const onDeleteArticle = async (row) => {
  await ElMessageBox.confirm('你确认要删除该分类么', '温馨提示', {
    type: 'warning',
    confirmButtonText: '确认',
    cancelButtonText: '取消'
  })
    .then(async () => {
      await artDelService(row.id)
      ElMessage.success('删除成功')
      articleList()
    })
    .catch(() => {
      ElMessage.info('用户取消了删除')
    })
}
</script>

<template>
  <el-card class="page-container">
    <template #header>
      <div class="header">
        <span>信息管理</span>
        <div class="extra">
          <el-button type="primary" @click="onAddArticle">添加信息</el-button>
        </div>
      </div>
    </template>

    <!-- 头部--搜索表单 -->
    <el-form inline>
      <el-form-item label="信息分类：">
        <!-- 子组件 v-model=:modelValue 和 @update:modelValue (props,emit)-->
        <channel-select
          v-model="params.categoryId"
          @categorys="getCategorys"
          style="width: 150px"
        ></channel-select>
      </el-form-item>

      <el-form-item label="发布状态：">
        <el-select
          placeholder="请选择"
          style="width: 150px"
          v-model="params.state"
        >
          <el-option label="已发布" value="已发布"></el-option>
          <el-option label="草稿" value="草稿"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSearch">搜索</el-button>
        <el-button @click="onReset">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 文章列表 -->
    <el-table :data="articles" style="width: 100%" v-loading="loading">
      <el-table-column label="信息标题" width="200" prop="title">
      </el-table-column>
      <el-table-column label="分类" prop="categoryName"></el-table-column>
      <el-table-column label="发表时间" prop="createTime">
        <template #default="{ row }">
          {{ formatTime(row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column label="状态" prop="state"></el-table-column>
      <el-table-column label="操作" width="100">
        <template #default="{ row }">
          <el-button
            :icon="Edit"
            circle
            plain
            type="primary"
            @click="onEditArticle(row)"
          ></el-button>
          <el-button
            :icon="Delete"
            circle
            plain
            type="danger"
            @click="onDeleteArticle(row)"
          ></el-button>
        </template>
      </el-table-column>
      <template #empty>
        <el-empty description="没有数据" />
      </template>
    </el-table>

    <!-- 添加编辑的抽屉 子组件-->
    <article-edit ref="articleEditRef" @success="onSuccess"></article-edit>

    <!-- 分页条 -->
    <el-pagination
      v-model:current-page="pageNum"
      v-model:page-size="pageSize"
      :page-sizes="[3, 5, 10, 15]"
      layout="jumper, total, sizes, prev, pager, next"
      background
      :total="total"
      @size-change="onSizeChange"
      @current-change="onCurrentChange"
      style="margin-top: 20px; justify-content: flex-end"
    />
  </el-card>
</template>
<style scoped>
.page-container {
  min-height: 100%;
  box-sizing: border-box;
}
.page-container .header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.el-table .cell {
  cursor: pointer;
}
</style>
